package appUtils;

import android.app.Activity;
import android.support.annotation.StringRes;
import android.widget.Toast;

/**
 * Created by zy on 2017/4/7.
 */

public class ToastUtil {
    private static Toast mToast;
    private static Activity mActivity;

    public static void init(Activity activity) {
        mActivity = activity;
        if (null == mToast) {
            mToast = Toast.makeText(mActivity, "", Toast.LENGTH_SHORT);
        }
    }

    public static void showLong(String str) {
        if (null == mToast) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        show(str, Toast.LENGTH_LONG);
    }

    public static void showLong(@StringRes int resId) {
        if (null == mToast) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        show(mActivity.getString(resId), Toast.LENGTH_LONG);
    }

    public static void showShort(String str) {
        if (null == mToast) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        show(str, Toast.LENGTH_SHORT);
    }

    public static void showShort(@StringRes int resId) {
        if (null == mToast) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        show(mActivity.getString(resId), Toast.LENGTH_SHORT);
    }

    private static void show(final String str, final int duration) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setDuration(duration);
                mToast.setText(str);
                mToast.show();
            }
        });
    }

}
